use dioxus::{logger::tracing, prelude::*};
use regex::Regex;
use crate::backend::spider_logic::{delete_spider_task, delete_spider_tasks, get_spider_tasks, save_spider_task, update_spider_task, run_spider_task};
use crate::entities::spider_task::SpiderTaskDTO;
use chrono::{Utc, TimeZone};
use crate::components::{Pagination, Dialog, DialogType, Alert, AlertType};

#[component]
pub fn Spider() -> Element {
    let mut show_modal = use_signal(|| false);
    let mut show_alert = use_signal(|| false);
    let mut alert_message = use_signal(String::new);
    let mut alert_type = use_signal(|| AlertType::Error);
    let mut show_delete_modal = use_signal(|| false);
    let mut show_batch_delete_modal = use_signal(|| false);
    let mut delete_task_id = use_signal(|| None::<i32>);
    let mut selected_tasks = use_signal(Vec::<i32>::new);
    let mut task_name = use_signal(String::new);
    let mut target_url = use_signal(String::new);
    let mut url_pattern = use_signal(String::new);
    let mut current_page = use_signal(|| 1u64);
    let mut tasks = use_signal(Vec::<SpiderTaskDTO>::new);
    let mut total_pages = use_signal(|| 0u64);
    let page_size = 10u64;

    let format_timestamp = move |timestamp: Option<i64>| -> String {
        match timestamp {
            Some(ts) => {
                let dt = Utc.timestamp_opt(ts, 0).unwrap();
                dt.format("%Y-%m-%d %H:%M:%S").to_string()
            }
            None => "-".to_string()
        }
    };

    let load_tasks = move || async move {
        match get_spider_tasks(*current_page.read(), page_size).await {
            Ok((task_list, pages)) => {
                tasks.set(task_list);
                total_pages.set(pages);
            }
            Err(err) => {
                tracing::error!("加载爬虫任务失败: {:?}", err);
            }
        }
    };

    use_effect(move || {
        to_owned![load_tasks];
        spawn(async move {
            load_tasks().await;
        });
    });
    let mut article_selector = use_signal(String::new);
    let mut breadcrumb_selector = use_signal(String::new);
    let mut rule_error = use_signal(|| None::<String>);
    let mut editing_task_id = use_signal(|| None::<i32>);
    let mut article_list_selector = use_signal(String::new);
    let mut article_title_selector = use_signal(String::new);
    
    let mut validate_regex = move |rule: &str| {
        if rule.is_empty() {
            rule_error.set(None);
            return;
        }
        match Regex::new(rule) {
            Ok(_) => rule_error.set(None),
            Err(_) => rule_error.set(Some("无效的正则表达式格式".to_string())),
        }
    };

    let mut open_modal = move |task: Option<SpiderTaskDTO>| {
        if let Some(task) = task {
            editing_task_id.set(Some(task.id));
            task_name.set(task.name);
            target_url.set(task.target_url);
            url_pattern.set(task.url_pattern);
            article_selector.set(task.article_selector);
            breadcrumb_selector.set(task.breadcrumb_selector);
            article_list_selector.set(task.article_list_selector);
            article_title_selector.set(task.article_title_selector);
        } else {
            editing_task_id.set(None);
        }
        show_modal.set(true);
    };
    let mut close_modal = move |_| {
        show_modal.set(false);
        editing_task_id.set(None);
        task_name.set(String::new());
        target_url.set(String::new());
        url_pattern.set(String::new());
        article_selector.set(String::new());
        breadcrumb_selector.set(String::new());
        article_list_selector.set(String::new());
        article_title_selector.set(String::new());
        rule_error.set(None);
    };

    let submit_form = move |e| async move {
        if task_name.read().is_empty() || target_url.read().is_empty() || url_pattern.read().is_empty() || article_selector.read().is_empty() || breadcrumb_selector.read().is_empty() {
            return;
        }

        if rule_error.read().is_some() {
            return;
        }

        let result = if let Some(id) = *editing_task_id.read() {
            update_spider_task(
                id,
                task_name.read().to_string(),
                target_url.read().to_string(),
                url_pattern.read().to_string(),
                article_list_selector.read().to_string(),
                article_title_selector.read().to_string(),
                article_selector.read().to_string(),
                breadcrumb_selector.read().to_string(),
            ).await
        } else {
            save_spider_task(
                task_name.read().to_string(),
                target_url.read().to_string(),
                url_pattern.read().to_string(),
                article_list_selector.read().to_string(),
                article_title_selector.read().to_string(),
                article_selector.read().to_string(),
                breadcrumb_selector.read().to_string(),
            ).await
        };

        match result {
            Ok(_) => {
                close_modal(e);
                to_owned![load_tasks];
                spawn(async move {
                    load_tasks().await;
                });
            },
            Err(err) => {
                tracing::error!("保存爬虫任务失败: {:?}", err);
                close_modal(e);
            }
        }
    };

    rsx! {
        div { class: "p-6",
            // 页面标题
            div { class: "flex justify-between items-center mb-6",
                h1 { class: "text-2xl font-semibold text-gray-900 dark:text-white", "爬虫任务管理" }
                button {
                    class: "px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700",
                    onclick: move |_| open_modal(None),
                    "新建任务"
                }
            }

            // 新建任务对话框
            Dialog {
                title: "新建爬虫任务".to_string(),
                show: *show_modal.read(),
                dialog_type: DialogType::Default,
                content: rsx! {
                    form {
                        class: "space-y-4",
                        div {
                            label {
                                class: "block text-sm font-medium text-gray-700 dark:text-gray-300",
                                "任务名称"
                            }
                            input {
                                class: "mt-1 block w-full rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-4 py-2 text-gray-900 dark:text-white focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 transition-colors duration-200",
                                "type": "text",
                                placeholder: "请输入任务名称",
                                value: task_name,
                                oninput: move |evt| task_name.set(evt.value())
                            }
                        }
                        div {
                            label {
                                class: "block text-sm font-medium text-gray-700 dark:text-gray-300",
                                "目标网站"
                            }
                            input {
                                class: "mt-1 block w-full rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-4 py-2 text-gray-900 dark:text-white focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 transition-colors duration-200",
                                "type": "url",
                                placeholder: "请输入目标网站URL",
                                value: target_url,
                                oninput: move |evt| target_url.set(evt.value())
                            }
                        }
                        div {
                            label {
                                class: "block text-sm font-medium text-gray-700 dark:text-gray-300",
                                "URL匹配规则"
                            }
                            textarea {
                                class: format_args!(
                                    "mt-1 block w-full rounded-lg border {} bg-white dark:bg-gray-700 px-4 py-2 text-gray-900 dark:text-white focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 transition-colors duration-200",
                                    if rule_error.read().is_some() { "border-red-500" } else { "border-gray-300 dark:border-gray-600" }
                                ),
                                rows: "3",
                                placeholder: "请输入URL匹配规则，例如：^https://example\\.com/article/\\d+$",
                                value: url_pattern,
                                oninput: move |evt| {
                                    let value = evt.value();
                                    url_pattern.set(value.clone());
                                    validate_regex(&value);
                                }
                            }
                            p { class: "mt-1 text-sm text-gray-500 dark:text-gray-400",
                                "提示：使用正则表达式来匹配需要爬取的文章页面URL"
                            }
                            {rule_error.read().as_ref().map(|err| {
                                rsx! {
                                    p { class: "mt-1 text-sm text-red-500", "{err}" }
                                }
                            })}
                        }
                        div {
                            label {
                                class: "block text-sm font-medium text-gray-700 dark:text-gray-300",
                                "文章选择器"
                            }
                            input {
                                class: "mt-1 block w-full rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-4 py-2 text-gray-900 dark:text-white focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 transition-colors duration-200",
                                "type": "text",
                                placeholder: "请输入文章内容选择器，例如：.article-content",
                                value: article_selector,
                                oninput: move |evt| article_selector.set(evt.value())
                            }
                            p { class: "mt-1 text-sm text-gray-500 dark:text-gray-400",
                                "提示：用于定位文章主体内容的CSS选择器"
                            }
                        }
                        div {
                            label {
                                class: "block text-sm font-medium text-gray-700 dark:text-gray-300",
                                "面包屑导航选择器"
                            }
                            input {
                                class: "mt-1 block w-full rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-4 py-2 text-gray-900 dark:text-white focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 transition-colors duration-200",
                                "type": "text",
                                placeholder: "请输入面包屑导航选择器，例如：.breadcrumb",
                                value: breadcrumb_selector,
                                oninput: move |evt| breadcrumb_selector.set(evt.value())
                            }
                            p { class: "mt-1 text-sm text-gray-500 dark:text-gray-400",
                                "提示：用于定位文章分类导航的CSS选择器"
                            }
                        }
                        div {
                            label {
                                class: "block text-sm font-medium text-gray-700 dark:text-gray-300",
                                "文章列表选择器"
                            }
                            input {
                                class: "mt-1 block w-full rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-4 py-2 text-gray-900 dark:text-white focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 transition-colors duration-200",
                                "type": "text",
                                placeholder: "请输入文章列表选择器，例如：.article-list",
                                value: article_list_selector,
                                oninput: move |evt| article_list_selector.set(evt.value())
                            }
                            p { class: "mt-1 text-sm text-gray-500 dark:text-gray-400",
                                "提示：用于定位文章列表的CSS选择器"
                            }
                        }
                        div {
                            label {
                                class: "block text-sm font-medium text-gray-700 dark:text-gray-300",
                                "文章标题选择器"
                            }
                            input {
                                class: "mt-1 block w-full rounded-lg border border-gray-300 dark:border-gray-600 bg-white dark:bg-gray-700 px-4 py-2 text-gray-900 dark:text-white focus:border-blue-500 focus:ring-2 focus:ring-blue-500 focus:ring-opacity-50 transition-colors duration-200",
                                "type": "text",
                                placeholder: "请输入文章标题选择器，例如：.article-title",
                                value: article_title_selector,
                                oninput: move |evt| article_title_selector.set(evt.value())
                            }
                            p { class: "mt-1 text-sm text-gray-500 dark:text-gray-400",
                                "提示：用于定位文章标题的CSS选择器"
                            }
                        }
                    }
                },
                on_confirm: move |e| submit_form(e),
                on_cancel: close_modal
            }

            // 批量操作按钮
            div { class: "mb-4 flex items-center space-x-4",
                div { class: "flex-grow" }
                button {
                    class: "px-3 py-1.5 bg-red-600 text-white text-sm rounded-md hover:bg-red-700 disabled:opacity-50 disabled:cursor-not-allowed",
                    disabled: selected_tasks.read().is_empty(),
                    onclick: move |_| show_batch_delete_modal.set(true),
                    "批量删除"
                }
            }

            // 任务列表
            div { class: "bg-white dark:bg-gray-800 shadow rounded-lg overflow-hidden",
                table { class: "min-w-full divide-y divide-gray-200 dark:divide-gray-700",
                    thead { class: "bg-gray-50 dark:bg-gray-700",
                        tr {
                            th { class: "px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider",
                                input {
                                    "type": "checkbox",
                                    class: "form-checkbox h-4 w-4 text-blue-600 transition duration-150 ease-in-out",
                                    checked: !tasks.read().is_empty() && tasks.read().len() == selected_tasks.read().len(),
                                    onclick: move |_| {
                                        if !tasks.read().is_empty() && tasks.read().len() == selected_tasks.read().len() {
                                            selected_tasks.set(Vec::new());
                                        } else {
                                            selected_tasks.set(tasks.read().iter().map(|t| t.id).collect());
                                        }
                                    }
                                }
                            }
                            th { class: "px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider", "任务名称" }
                            th { class: "px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider", "目标网站" }
                            th { class: "px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider", "状态" }
                            th { class: "px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider", "上次执行" }
                            th { class: "px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider", "爬取数量" }
                            th { class: "px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-300 uppercase tracking-wider", "操作" }
                        }
                    }
                    tbody { class: "bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700",
                        {
                            let tasks_data = tasks.read().to_vec();
                            rsx! {
                                for task in tasks_data {
                                    tr {
                                        td { class: "px-6 py-4 whitespace-nowrap",
                                            input {
                                                "type": "checkbox",
                                                class: "form-checkbox h-4 w-4 text-blue-600 transition duration-150 ease-in-out",
                                                checked: selected_tasks.read().contains(&task.id),
                                                onclick: move |_| {
                                                    let mut selected = selected_tasks.read().to_vec();
                                                    if selected_tasks.read().contains(&task.id) {
                                                        selected.retain(|&x| x!= task.id);
                                                    } else {
                                                        selected.push(task.id);
                                                    }
                                                    selected_tasks.set(selected);
                                                }
                                            }
                                        }
                                        td { class: "px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white", "{task.name}" }
                                        td { class: "px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white", "{task.target_url}" }
                                        td { class: "px-6 py-4 whitespace-nowrap",
                                            span { 
                                                class: format_args!(
                                                    "px-2 inline-flex text-xs leading-5 font-semibold rounded-full {}",
                                                    match task.status {
                                                        0 => "bg-yellow-100 text-yellow-800",
                                                        2 => "bg-green-100 text-green-800",
                                                        3 => "bg-blue-100 text-blue-800",
                                                        4 => "bg-red-100 text-red-800",
                                                        _ => "bg-gray-100 text-gray-800"
                                                    }
                                                ),
                                                match task.status {
                                                    0 => "待执行",
                                                    1 => "运行中",
                                                    2 => "已完成",
                                                    _ => "未知状态"
                                                }
                                            }
                                        }
                                        td { class: "px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white", "{format_timestamp(task.last_run_at)}" }
                                        td { class: "px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-white", "{task.crawled_count}" }
                                        td { class: "px-6 py-4 whitespace-nowrap text-sm font-medium",
                                            {
                                                let task_id = task.id;
                                                let task_status = task.status.clone();
                                                let task = task.clone();
                                                rsx! {
                                                    button {
                                                        class: "text-blue-600 hover:text-blue-900 mr-3",
                                                        onclick: move |_| open_modal(Some(task.clone())),
                                                        "编辑"
                                                    }
                                                    button { 
                                                        class: "text-blue-600 hover:text-blue-900 mr-3",
                                                        disabled: task_status == 2,
                                                        onclick: move |_| {
                                                            to_owned![load_tasks];
                                                            spawn(async move {
                                                                match run_spider_task(task_id).await {
                                                                    Ok(_) => {
                                                                        load_tasks().await;
                                                                    }
                                                                    Err(e) => {
                                                                        alert_message.set(format!("运行爬虫任务失败: {}", e));
                                                                        alert_type.set(AlertType::Error);
                                                                        show_alert.set(true);
                                                                    }
                                                                }
                                                            });
                                                        },
                                                        "运行" 
                                                    }
                                                    button { 
                                                        class: "text-red-600 hover:text-red-900",
                                                        onclick: move |_| {
                                                            delete_task_id.set(Some(task_id));
                                                            show_delete_modal.set(true);
                                                        },
                                                        "删除" 
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        Alert {
                            message: alert_message.read().clone(),
                            show: show_alert.read().clone(),
                            alert_type: alert_type.read().clone(),
                            on_close: move |_| show_alert.set(false)
                        }
                        
                    }
                }
            }

            // 删除确认对话框
            Dialog {
                title: "删除爬虫任务".to_string(),
                show: *show_delete_modal.read(),
                dialog_type: DialogType::Warning,
                content: rsx! {
                    p {
                        class: "text-sm text-gray-500 dark:text-gray-400",
                        "确定要删除这个爬虫任务吗？此操作无法撤销。"
                    }
                },
                on_confirm: move |_| {
                    if let Some(id) = *delete_task_id.read() {
                        to_owned![load_tasks];
                        spawn(async move {
                            if let Ok(_) = delete_spider_task(id).await {
                                load_tasks().await;
                            }
                        });
                    }
                    show_delete_modal.set(false);
                    delete_task_id.set(None);
                },
                on_cancel: move |_| {
                    show_delete_modal.set(false);
                    delete_task_id.set(None);
                }
            }

            // 批量删除确认对话框
            Dialog {
                title: "批量删除爬虫任务".to_string(),
                show: *show_batch_delete_modal.read(),
                dialog_type: DialogType::Warning,
                content: rsx! {
                    p {
                        class: "text-sm text-gray-500 dark:text-gray-400",
                        "确定要删除选中的 {selected_tasks.read().len()} 个爬虫任务吗？此操作无法撤销。"
                    }
                },
                on_confirm: move |_| {
                    let selected = selected_tasks.read().to_vec();
                    to_owned![load_tasks];
                    spawn(async move {
                        if let Ok(_) = delete_spider_tasks(selected).await {
                            load_tasks().await;
                        }
                    });
                    show_batch_delete_modal.set(false);
                    selected_tasks.set(Vec::new());
                },
                on_cancel: move |_| {
                    show_batch_delete_modal.set(false);
                }
            }

            // 分页控制
            Pagination {
                current_page: *current_page.read(),
                total_pages: *total_pages.read(),
                on_page_change: move |page| {
                    current_page.set(page);
                    to_owned![load_tasks];
                    spawn(async move {
                        load_tasks().await;
                    });
                }
            }
        }
    }
}